const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
require('dotenv').config();

const app = express();

// 中间件
app.use(cors({
  origin: process.env.FRONTEND_URL || '*',
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

// 增加请求体大小限制
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));

// API路由
app.use('/api/auth', require('./routes/auth'));
app.use('/api/albums', require('./routes/albums'));
app.use('/api/photos', require('./routes/photos'));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads'), {
  setHeaders: (res, path) => {
    res.set('Cache-Control', 'public, max-age=31536000');
    res.set('Access-Control-Allow-Origin', '*');
  }
}));

app.use('/uploads/thumbnails', express.static(path.join(__dirname, 'uploads/thumbnails'), {
  setHeaders: (res, path) => {
    res.set('Cache-Control', 'public, max-age=31536000');
  }
}));

app.use('/uploads/previews', express.static(path.join(__dirname, 'uploads/previews'), {
  setHeaders: (res, path) => {
    res.set('Cache-Control', 'public, max-age=31536000');
    res.set('Access-Control-Allow-Origin', '*');
  }
}));

// 添加前端构建文件的静态服务
app.use(express.static(path.join(__dirname, 'public'), {
  index: false,
  setHeaders: (res, filePath) => {
    if (filePath.endsWith('.js')) {
      res.set('Content-Type', 'application/javascript');
    } else if (filePath.endsWith('.css')) {
      res.set('Content-Type', 'text/css');
    }
  }
}));

// 处理静态资源请求
app.use('/static', express.static(path.join(__dirname, 'public/static'), {
  setHeaders: (res, filePath) => {
    if (filePath.endsWith('.js')) {
      res.set('Content-Type', 'application/javascript');
    } else if (filePath.endsWith('.css')) {
      res.set('Content-Type', 'text/css');
    }
  }
}));

// 添加健康检查端点
app.get('/health', (req, res) => {
  res.status(200).json({ 
    status: 'ok',
    apiUrl: process.env.REACT_APP_API_URL,
    frontendUrl: process.env.FRONTEND_URL
  });
});

// 所有其他请求返回前端应用
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 添加错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  console.error('错误堆栈:', err.stack);
  res.status(500).json({ 
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 添加404处理中间件
app.use((req, res) => {
  console.error('404 Not Found:', req.url);
  res.status(404).json({ message: '请求的资源不存在' });
});

// 连接数据库
const connectDB = async () => {
  const maxRetries = 5;
  let retries = 0;
  
  while (retries < maxRetries) {
    try {
      const mongoURI = process.env.MONGODB_URI;
      if (!mongoURI) {
        throw new Error('MONGODB_URI 环境变量未设置');
      }
      console.log(`正在连接 MongoDB (尝试 ${retries + 1}/${maxRetries}):`, mongoURI);
      
      await mongoose.connect(mongoURI, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        serverSelectionTimeoutMS: 5000,
        socketTimeoutMS: 45000,
        family: 4
      });
      
      console.log('MongoDB 连接成功');
      return;
    } catch (error) {
      retries++;
      console.error(`MongoDB 连接错误 (尝试 ${retries}/${maxRetries}):`, error.message);
      console.error('错误堆栈:', error.stack);
      
      if (retries === maxRetries) {
        console.error('达到最大重试次数，退出程序');
        process.exit(1);
      }
      
      console.log(`等待 5 秒后重试...`);
      await new Promise(resolve => setTimeout(resolve, 5000));
    }
  }
};

// 启动服务器
const startServer = async () => {
  try {
    await connectDB();
    const PORT = process.env.BACKEND_PORT || process.env.PORT || 5000;
    const HOST = process.env.HOST || '0.0.0.0';
    
    app.listen(PORT, HOST, () => {
      const displayHost = (HOST === '0.0.0.0' || HOST === '::') ? 'localhost' : HOST;
      console.log(`服务器运行在 http://${displayHost}:${PORT}`);
      console.log('环境:', process.env.NODE_ENV);
      console.log('MongoDB URI:', process.env.MONGODB_URI);
      console.log('Public IP:', process.env.PUBLIC_IP);
      console.log('API URL:', process.env.REACT_APP_API_URL);
    });
  } catch (error) {
    console.error('服务器启动错误:', error);
    console.error('错误堆栈:', error.stack);
    process.exit(1);
  }
};

startServer(); 